package com.eet.juc.utils;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 信号量Demo
 *
 * @author zheng.zhang
 */
@SuppressWarnings("all")
public class SemaphoreDemo {
    private static final ExecutorService SERVICE = Executors.newFixedThreadPool(6);

    public static void main(String[] args) {
        // 总共有三个停车位
        Semaphore semaphore = new Semaphore(3);
        // 创建6个线程去抢停车位
        for (int i = 0; i < 6; i++) {
            final int tempI = i;
            SERVICE.submit(() -> {
                try {
                    // 获取信号量
                    semaphore.acquire();
                    // 抢到车位
                    System.out.println(Thread.currentThread().getName().concat("抢到车位"));
                    TimeUnit.SECONDS.sleep(2);

                    System.out.println(Thread.currentThread().getName().concat("离开车位"));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    // 释放信号量
                    semaphore.release();
                    if (tempI == 5) {
                        SERVICE.shutdownNow();
                    }
                }
            });
        }
    }
}
